package com.example.sicnuaccountingapp.ui.profile

import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.viewModels
import com.example.sicnuaccountingapp.R
import com.example.sicnuaccountingapp.databinding.DialogEditProfileBinding
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class EditProfileDialog : DialogFragment() {
    private var _binding: DialogEditProfileBinding? = null
    private val binding get() = _binding!!

    private val viewModel: ProfileViewModel by viewModels({ requireParentFragment() })

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        _binding = DialogEditProfileBinding.inflate(LayoutInflater.from(context))

        setupInitialValues()

        return AlertDialog.Builder(requireContext())
            .setTitle(R.string.edit_profile)
            .setView(binding.root)
            .setPositiveButton(R.string.save, null)
            .setNegativeButton(R.string.cancel, null)
            .create()
            .apply {
                setOnShowListener { dialog ->
                    (dialog as AlertDialog).getButton(AlertDialog.BUTTON_POSITIVE)
                        .setOnClickListener {
                            saveProfile()
                        }
                }
            }
    }

    private fun setupInitialValues() {
        val currentState = viewModel.state.value
        if (currentState is ProfileUiState.Success) {
            binding.apply {
                usernameEdit.setText(currentState.user.username)
                emailEdit.setText(currentState.user.email)
                phoneEdit.setText(currentState.user.phone)
            }
        }
    }

    private fun saveProfile() {
        val username = binding.usernameEdit.text.toString()
        if (username.isBlank()) {
            Toast.makeText(context, R.string.username_cannot_be_empty, Toast.LENGTH_SHORT).show()
            return
        }

        viewModel.updateProfile(
            username = username,
            email = binding.emailEdit.text.toString().takeIf { it.isNotBlank() },
            phone = binding.phoneEdit.text.toString().takeIf { it.isNotBlank() }
        )
        dismiss()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    companion object {
        const val TAG = "EditProfileDialog"

        fun newInstance(): EditProfileDialog {
            return EditProfileDialog()
        }
    }
} 